<?php

class ImgUpLauder{

	function uploadPhotos($index, $newWidth, $newHeight, $sourceFile ,$destDir, $mimeType, $crop=false){
        $destinationFile ='';
        $photo_id = microtime();
        $photo = $photo_id .'_'.$index;
        $destinationFile = BASEURL.$destDir.$photo;

        $gdFunctionSuffix= array('image/pjpeg'=> 'JPEG', 'image/jpeg'=> 'JPEG', 'image/gif'=> 'GIF', 'image/png'=> 'PNG');
		$functionSuffix= $gdFunctionSuffix[$mimeType];
		$functionToRead= 'ImageCreateFrom'. $functionSuffix;
		$sourceHandler= @$functionToRead($sourceFile);
		if(!$sourceHandler){
			return false;
		}
		$x= 0;
		$y= 0;
		$width= $newWidth;
		$height= $newHeight;
		list($imageWidth, $imageHeight)= getimagesize($sourceFile);
		if(!$crop){
			// original resize to fit in frame ($newWidth x $newHeight)
			$ratio= $imageWidth / $imageHeight;
			if($newWidth / $newHeight > $ratio){
				$newWidth= floor($newHeight * $ratio);
			}else{
				$newHeight= floor($newWidth / $ratio);
			}
			$width= $newWidth;
			$height= $newHeight;
		}
		elseif(($imageWidth > $newWidth) || ($imageHeight > $newHeight)){
			// crop ant fit into frame
			$ratio= $imageWidth / $imageHeight;
			if($width / $height < $ratio){
				$width= floor($height * $ratio);
			}
			else{
				$height= floor($width / $ratio);
			}
			$x= ($newWidth - $width)/2;
			$y= ($newHeight - $height)/2;
		}
		else{
			// do not crop, just put in center if smaller
			$x= ($newWidth - $imageWidth)/2;
			$y= ($newHeight - $imageHeight)/2;
			$width= $imageWidth;
			$height= $imageHeight;
		}
		$destinationHandle= ImageCreateTrueColor($newWidth, $newHeight);
		$white= ImageColorAllocate($destinationHandle, 255, 255, 255); // baltas fonas
		ImageFill($destinationHandle, 0, 0, $white);
		ImageCopyResampled($destinationHandle, $sourceHandler, $x, $y, 0, 0, $width, $height, $imageWidth, $imageHeight);
		ImageJPEG($destinationHandle, $destinationFile, 76);
		// Clear image cache
		@ImageDestroy($destinationHandle);
		@ImageDestroy($sourceHandler);
		return $destDir.$photo;
	}
}
?>